/**
 * @file server.cpp
 * @brief Server class methods implementation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * @author VestniK (Sergey N.Vidyuk) sir.vestnik@gmail.com
 * @date 17 Oct 2008
 */
#include "server.h"

#include "session.h"
#include "defaults.h"
#include "logger.h"
#include "sessionfactory.h"

using namespace mjn;

Server::Server(quint16 port) {
    if ( port == 0 ) {
        QSettings settings;
        port = settings.value("port",DEFAULT_PORT).value<quint16>();
    }
    mTcpServer.setMaxPendingConnections(PLAYERS_COUNT);
    if ( ! mTcpServer.listen(QHostAddress::Any, port) ) {
        log()->error(Logger::Network,
                     tr("Unable to bind TCP port '%1' for listening.").arg(port) );
        qApp->quit();
    }
    mSessionFactory = new SessionFactory(&mGame);
    connect(&mTcpServer,SIGNAL( newConnection() ),
            this,SLOT( onTcpConnection() ));
    log()->info(Logger::Network,
                tr("Waiting for incomming connections on TCP port '%1'.").arg(port) );
}

Server::~Server() {
}

void Server::onTcpConnection() {
    QTcpSocket *socket = mTcpServer.nextPendingConnection();
    if ( socket == 0 ) return;
    log()->info(Logger::Network,
                tr("New incomming connection from '%1'").arg(socket->peerAddress().toString()) );
    Session *session = mSessionFactory->create();
    session->setSocket(socket);
    connect(socket,SIGNAL(disconnected()),
            session,SLOT(deleteLater()));
}
